# 59.110.126.169

from elasticsearch import Elasticsearch,helpers


es = Elasticsearch([{"host": "59.110.126.169", "port": 9200}])


index_name = "shopping"


# try:
#     if es.indices.create(index=index_name):
#         print(f"索引 {index_name} 创建成功")
# except Exception as e:
#     print(f"创建索引时出错: {e}")


# 设置映射
# index_name = "shopping"
# mapping = {
#         "properties": {
#                 "id": {
#                     "type": "keyword"
#                 },
#                 "name":{
#                     "type": "text"
#                 },
#                 "pid":{
#                     "type": "keyword"
#                 },
#                 "topid":{
#                     "type": "keyword"
#                 },
#             }
#         }
#
# try:
#     if es.indices.put_mapping(index=index_name, body=mapping):
#         print(f"索引 {index_name} 创建成功")
# except Exception as e:
#     print(f"创建索引时出错: {e}")


# 插入数据
# product_data = {
#     "name": "日常保洁",
#     'id':1,
#     'pid':2,
#     'topid':1
#
# }
# try:
#     result = es.index(index=index_name, body=product_data)
#     print(f"商品信息插入结果: {result}")
# except Exception as e:
#     print(f"插入商品信息出错: {e}")


# query = {
#     "query": {
#         "match": {
#             "name": "日常"
#         }
#     }
# }
# try:
#     result = es.search(index=index_name, body=query)
#     print(result)
#     for hit in result["hits"]["hits"]:
#         print("文档ID:", hit["_id"])
#         print("文档内容:", hit["_source"])
# except Exception as e:
#     print(f"查询出错: {e}")

# 假设您已经知道要删除的文档的 _id，这里以 'example_id' 为例
# document_id_to_delete = 'S9Km_ZMB6Qgr5VCPgfze'  # 替换为实际的文档 ID
#
# try:
#     # 调用 delete 方法删除文档
#     response = es.delete(index=index_name, id=document_id_to_delete)
#     print(f"删除结果: {response}")
# except Exception as e:
#     print(f"删除文档时出错: {e}")



class ElasticsearchClient:
    def __init__(self):
        self.client = Elasticsearch([{'host': "59.110.126.169", 'port': 9200}])
        self.index_name = "shopping"

    def add_documents(self, data):
        try:
            helpers.bulk(self.client, actions=data, index=self.index_name)
            print('添加成功')
        except Exception as e:
            print(f"添加失败: {e}")


    def search(self,name,sales,topid,page):
        match_list = []
        order_list = []
        if name is not None and name != '':
            name_query = {
                "match": {
                    "name": name
                }
            }
            match_list.append(name_query)
        if sales == 1:
            sales_order = {
                "sales": {
                    "order": "asc"
                }
            }
            order_list.append(sales_order)
        if sales == 2:
            sales_order = {
                "sales": {
                    "order": "desc"
                }
            }
            order_list.append(sales_order)

        if topid != 0:
            topid_query = {
                "term": {
                    "topid": topid
                }
            }
            match_list.append(topid_query)

        query = {
            "query": {
                "bool": {
                    "must": [],
                    'should': [],
                }
            },
            'from': (int(page)-1)*5,
            'size':5,
            "sort": [],
        }

        if len(match_list) > 0:
            query['query']['bool']['must'] = match_list
        else:
            query['query']['bool']['must'] = [{"match_all": {}}]
        if len(order_list) > 0:
            query['sort'] = order_list

        try:
            result = self.client.search(index=self.index_name, body=query)
            print(result)
            hits = result['hits']['hits']
            total = result['hits']['total']['value']
            data = [item['_source'] for item in hits]
            return total,data
        except Exception as e:
            print(f"查询出错: {e}")












el = ElasticsearchClient()